﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Common;

namespace DataAccess
{
    public class UsersRepository : ConnectionClass
    {
        public UsersRepository() : base() { }

        public User GetUser(string username)
        {
            return entities.Users.SingleOrDefault(u => u.Username == username);
        }

        public IQueryable<User> GetUsernames()
        {
            return entities.Users.AsQueryable();
        }

        public bool DoesUsernameExist(string username)
        {
            if (entities.Users.Count(u => u.Username == username) == 0)
            {
                return false;
            }
            else return true;
        }

        public bool DoesEmailExist(string email)
        {
            if (entities.Users.Count(u => u.Email == email) == 0)
            {
                return false;
            }
            else return true;
        }

        public Role GetRole(int roleId)
        {
            return entities.Roles.SingleOrDefault(x => x.UserTypeID == roleId);
        }

        public void Register(User newUser)
        {
            entities.AddToUsers(newUser);
            newUser.Roles.Add(GetRole(1));
            entities.SaveChanges();
        }

        //method to check whether the user exists
        public bool IsAuthenticationValid(string username, string password)
        {
            if (entities.Users.SingleOrDefault(x => x.Username == username && x.Password == password) == null)
            {
                //Does not exist
                return false;
            }
            else
            {
                return true;
            }
        }

        

    }
}
